//
//  OASendOrderApplyViewController.m
//  XTCloud
//
//  Created by QA on 2017/10/30.
//  Copyright © 2017年 ShangHai HaoLei Software Technology Co., Ltd. All rights reserved.
//

#import "OASendOrderApplyViewController.h"

#import "GEDateTextField.h"
#import "GEPickerTextField.h"
#import "FileUploadModel.h"
#import "FileSizeFormatHelper.h"
#import "FileTypeIcon.h"
#import "GEObjectButton.h"
#import "GEInputTableViewCell.h"
#import "GEPickerTextField.h"

#import "ServiceConnect.h"
#import "UserLoginNSCoding.h"
#import "NSKeyedArchiverUserLogin.h"
#import "NSDictionary+DataFormat.h"

#import "OASendApplyNodeViewCell.h"

#import "UploadViewController.h"
#import "ThreeDataViewController.h"
#import "OASendApplyClassViewController.h"
#import "PreviewLocalFileHelper.h"

#import "OASendApplyHtmlViewController.h"
#import "AutoTextTableViewCell.h"

@interface OASendOrderApplyViewController()

@property (nonatomic, strong) NSMutableArray *accessoryArray;
@property (nonatomic, assign) BOOL isUndertakes;

@property (nonatomic, strong) NSString *processId;//流程ID
@property (nonatomic, strong) NSString *templateId;//类型ID(订单ID)

@property (nonatomic, strong) NSMutableArray *appleNodeArray;
@property (nonatomic,strong) NSMutableArray *appleModeData;
@property (nonatomic,assign) NSInteger appleContentState;//0加载中，1未找到数据，2加载失败，3加载成功

@end


@implementation OASendOrderApplyViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        [self setTitle: @"新建申请"];
        
        UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithTitle:@"提交" style:UIBarButtonItemStyleDone target:self
                                                                      action:@selector(uploadApplySelector:)];
        self.navigationItem.rightBarButtonItem = leftButton;
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.accessoryArray = [NSMutableArray array];
    self.appleNodeArray = [NSMutableArray array];
    self.appleModeData = [NSMutableArray array];
    
    self.tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SuperWidth, 10)];
    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SuperWidth, 10)];
    
    //获取订单基本数据
    [self getOrderBascInfo];
    
    //获取节点信息
    [self getFlowNetWorkData];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//添加文件
- (void)drawRowFileCell:(UITableViewCell*)cell model:(FileUploadModel *)model indexPath:(NSIndexPath *)indexPath
{
    CGSize cellSize = cell.frame.size;
    
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 5, cellSize.height - 10, cellSize.height - 10)];
    imageView.image = [FileTypeIcon setFileTypeIcon:model.filePath];
    [cell.contentView addSubview:imageView];
    
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(cellSize.height + 5, 3, cellSize.width - cellSize.height - 60, cellSize.height/2)];
    titleLabel.text = model.fileName;
    titleLabel.font = [UIFont systemFontOfSize:15.0];
    titleLabel.lineBreakMode = NSLineBreakByTruncatingMiddle;
    titleLabel.textAlignment = NSTextAlignmentLeft;
    titleLabel.textColor = [UIColor darkGrayColor];
    [cell.contentView addSubview:titleLabel];
    
    NSString *fileSize = [FileSizeFormatHelper getFileSizeString:[NSString stringWithFormat:@"%lld",model.fileSize]];
    UILabel *field = [[UILabel alloc] initWithFrame:CGRectMake(cellSize.height + 5, cellSize.height/2 - 2, cellSize.width - cellSize.height - 10, cellSize.height/2)];
    field.font = [UIFont systemFontOfSize:12.0];
    field.text = [NSString stringWithFormat:@"文件大小：%@", fileSize] ;
    field.textColor = [UIColor darkGrayColor];
    [cell.contentView addSubview:field];
    
    GEObjectButton *button = [GEObjectButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(cellSize.width - 50, 0, cellSize.height, cellSize.height);
    [button setImage:[UIImage imageNamed:@"del.png"] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(delFileSelector:) forControlEvents:UIControlEventTouchUpInside];
    button.object = @[@(indexPath.section), model];
    [cell.contentView addSubview:button];
    
    //添加分割线
    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, cell.frame.size.height - 1, SuperWidth, 1)];
    lineView.backgroundColor = [UIColor groupTableViewBackgroundColor];
    [cell.contentView addSubview:lineView];
}

#pragma mark - UIAlertView

- (void)showAlertView:(NSString*)message
{
    UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"温馨提示" message:message delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
    alert.alertViewStyle=UIAlertViewStyleDefault;
    [alert show];
}


#pragma mark
#pragma mark - 申请数据验证

- (void)uploadApplySelector:(id)selector
{
    //关闭键盘
    [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
    
    //编辑审批流程节点
    BOOL isFinishEdit = YES;
    if(self.appleNodeArray && self.appleNodeArray.count>0){
        for(NSDictionary *mDictionary in self.appleNodeArray){
            BOOL rankIdstatus = [[mDictionary objectForKey:@"rankIdstatus"] boolValue];
            NSInteger postid = [[mDictionary objectForKey:@"postid"] integerValue];
            if (rankIdstatus && postid == 0) isFinishEdit = NO;
        }
    }
    
    if (!(self.appleNodeArray && self.appleNodeArray.count>0)){
        [self showAlertView:@"没有找到审批节点，请选择审批流程"];
    } else if (!isFinishEdit){
        [self showAlertView:@"请\"编辑\"审批流程节点"];
    } else {
        //是否开启代发（NO）
        UserLoginNSCoding *userInfo = [NSKeyedArchiverUserLogin getUserLoginData];
        NSString *orgId = userInfo.CorpId;
        NSString *deptId = userInfo.DeptId;
        
        //数据集合
        NSMutableArray *data = [NSMutableArray array];
        [data addObject:orgId];//公司id
        [data addObject:deptId];//部门id
        [data addObject:[NSString stringWithFormat:@"%d",NO]];//是否代发
        
        [data addObject:@"0"];//模板id
        [data addObject:@"0"];//流程id
        
        [data addObject:self.appleNodeArray];//流程节点
        [data addObject:self.accessoryArray];//附件
        
        [self submitApplySelector:data];
    }
}

#pragma mark
#pragma mark - 申请提交验证

- (void)submitApplySelector:(NSArray*)applyArray
{
    //获取首个审批节点
    NSArray *applyFirstNodeArray = applyArray[5];
    NSDictionary *applyFirstNode = [applyFirstNodeArray firstObject];
    NSString *approvalNodeId = [applyFirstNode objectFormatStringForKey:@"id"];
    
    //处理节点信息
    NSString *jsonNodeString = nil;
    NSMutableArray *jsonNodeArray = [NSMutableArray array];
    for(NSDictionary *jsonDictionary in applyFirstNodeArray){
        NSMutableDictionary *mDictionary = [NSMutableDictionary dictionary];
        [mDictionary setObject:[jsonDictionary objectFormatForKey:@"id"] forKey:@"id"];
        [mDictionary setObject:[jsonDictionary objectFormatForKey:@"tnodename"] forKey:@"tNodeName"];
        [mDictionary setObject:[jsonDictionary objectFormatForKey:@"tnodetype"] forKey:@"tNodeType"];
        [mDictionary setObject:[jsonDictionary objectFormatForKey:@"postid"] forKey:@"postId"];
        [mDictionary setObject:[jsonDictionary objectFormatForKey:@"rankId"] forKey:@"rankId"];
        [jsonNodeArray addObject:mDictionary];
    }
    if ([NSJSONSerialization isValidJSONObject:jsonNodeArray]) {
        NSError *error;
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonNodeArray options:NSJSONWritingPrettyPrinted error:&error];
        jsonNodeString =[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    }
    
    //处理附件信息
    NSString *jsonFileString = nil;
    NSArray *accessoryArray = applyArray[6];
    NSMutableArray *jsonFileArray = [NSMutableArray array];
    for(FileUploadModel *model in accessoryArray){
        NSDictionary *jsonDictionary = [model getFileInfo];
        NSMutableDictionary *mDictionary = [NSMutableDictionary dictionary];
        [mDictionary setObject:[jsonDictionary objectFormatForKey:@"filePath"] forKey:@"FJPath"];
        [mDictionary setObject:[jsonDictionary objectFormatForKey:@"fileName"] forKey:@"FJName"];
        [jsonFileArray addObject:mDictionary];
    }
    if ([NSJSONSerialization isValidJSONObject:jsonFileArray]) {
        NSError *error;
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonFileArray options:NSJSONWritingPrettyPrinted error:&error];
        jsonFileString =[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    }
    
    NSDictionary *orderInfo = self.value;
    NSString *orderId = [orderInfo objectFormatStringForKey:@"ID"];//订单ID
    
    //数据处理，打包上传
    UserLoginNSCoding *userInfo = [NSKeyedArchiverUserLogin getUserLoginData];
    ServiceParametModel *model = [[ServiceParametModel alloc] init];
    [model setValue:userInfo.Id forKey:@"userid"];
    [model setValue:approvalNodeId forKey:@"approvalNodeId"];//首个审批节点
    [model setValue:self.templateId forKey:@"templateId"];//模板id
    [model setValue:self.processId forKey:@"processId"];//流程id
    [model setValue:@"[]" forKey:@"FieldValues"];//流程节点
    [model setValue:jsonNodeString forKey:@"nodeList"];//申请表节点
    [model setValue:jsonFileString forKey:@"files"]; //附件
    [model setValue:orderId forKey:@"id"]; //订单ID
    [model setValue:@"SPJZL" forKey:@"appType"]; //类型
    
    ServiceConnect *content = [[ServiceConnect alloc] initWithMethodName:@"OA_SendApproval_Bus" dataArray:model];
    [content showMBProgressHUD:self.navigationController labelText:@"正在提交"];
    [content startConnectNetworkCompleted:^(ServiceResultModel *result, NSDictionary *userInfo) {
        if(result.resultArray && result.resultArray.count>0){
            //result：返回结果(1成功，0失败)
            NSDictionary *resultArray = [result.resultArray firstObject];
            NSInteger result = [[resultArray objectFormatForKey:@"result"] integerValue];
            if (result == 0) [self setAlertViewMessage:@"提交失败，请重新尝试"];
            else [self successUpLoadBriefcase];
            
        } else {
            [self setAlertViewMessage:@"提交申请失败，请重新尝试提交"];
        }
    } failed:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"==failed===%@",error);
        [self setAlertViewMessage:@"提交申请失败，请重新尝试提交"];
        
    } abnormal:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"===abnormal==%@",error);
        [self setAlertViewMessage:@"网络异常，请检查网络是否连接正常"];
    }];
}

#pragma mark
#pragma mark - UIAlertView

- (void)setAlertViewMessage:(NSString*)message
{
    UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"温馨提示" message:message delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
    alert.alertViewStyle=UIAlertViewStyleDefault;
    [alert show];
}

- (void)successUpLoadBriefcase
{
    UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"提交申请成功，请耐心等待审批" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
    alert.alertViewStyle=UIAlertViewStyleDefault;
    [alert show];
}

#pragma mark
#pragma mark - UIAlertViewDelegate

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    MainAppDelegate *mDelegate = [[UIApplication sharedApplication] delegate];
    NSArray *viewControllers = mDelegate.navigationController.viewControllers;
    UIViewController *closeController = [viewControllers objectAtIndex:viewControllers.count - 3];
    [mDelegate.navigationController popToViewController:closeController animated:YES];
}

#pragma mark
#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if(section == 0) {
        return 1;
    } else if(section == 1) {
        return self.appleNodeArray.count>0 ? self.appleNodeArray.count : 1;
    } else if(section == 2) {
        return self.accessoryArray.count + 1;
    }
    
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *CellIdentifier = [NSString stringWithFormat:@"OAUploadBriefcaseViewCell%ld%ld",indexPath.section,indexPath.row];
    
    if(indexPath.section == 0){
        if (self.appleContentState == 3) {
            AutoTextTableViewCell *cell = [[AutoTextTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"AutoTextTableViewCellApple"];
            cell.isChangeWidth = YES;
            [cell setDataArray:self.appleModeData];
            return cell;
            
        } else {
            UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"ActivityIndicatss"];
            cell.contentView.frame = CGRectMake(0, 0, cell.contentView.frame.size.width, 54);
            
            if(self.appleContentState == 0) {//加载进度条
                UIActivityIndicatorView *act=[[UIActivityIndicatorView  alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
                act.center = CGPointMake(SuperWidth/2, 27.0f);
                act.activityIndicatorViewStyle=UIActivityIndicatorViewStyleGray;
                act.hidesWhenStopped = YES;
                [act startAnimating];
                [cell.contentView addSubview:act];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                
            } else if(self.appleContentState == 1){//显示无数据提示
                UILabel* label = [[UILabel alloc] initWithFrame:cell.contentView.frame];
                label.center = CGPointMake(SuperWidth/2, cell.contentView.frame.size.height/2);
                label.text = @"未找到审批模板内容";
                label.font = [UIFont fontWithName:@"Arial" size:16];
                label.textColor = [UIColor lightGrayColor];
                label.textAlignment = NSTextAlignmentCenter;
                [cell.contentView addSubview:label];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                
            } else if(self.appleContentState == 2){//显示失败提示
                UILabel* label = [[UILabel alloc] initWithFrame:cell.contentView.frame];
                label.center = CGPointMake(SuperWidth/2, cell.contentView.frame.size.height/2);
                label.text = @"加载失败，点击重试";
                label.font = [UIFont fontWithName:@"Arial" size:16];
                label.textColor = [UIColor lightGrayColor];
                label.textAlignment = NSTextAlignmentCenter;
                [cell.contentView addSubview:label];
            }
            return cell;
        }
    }
    
    //审批流程
    else if(indexPath.section == 1){
        if (self.appleNodeArray.count <= 0) {
            GEInputTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
            if (cell == nil) cell = [[GEInputTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
            
            //移除其他控件
            for(UIView *view in cell.contentView.subviews){
                if([view isKindOfClass:[UIActivityIndicatorView class]]){
                    UIActivityIndicatorView *act = (UIActivityIndicatorView*)view;
                    [act stopAnimating];
                }
                [view removeFromSuperview];
            }
            
            if(cell.tag == -1) {//加载进度条
                UIActivityIndicatorView *act=[[UIActivityIndicatorView  alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
                act.center = CGPointMake(SuperWidth/2, 22.0f);
                act.activityIndicatorViewStyle=UIActivityIndicatorViewStyleGray;
                //act.hidesWhenStopped = YES;
                [act startAnimating];
                [cell.contentView addSubview:act];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                
            } else if(cell.tag == -2){//显示失败提示
                UILabel* label = [[UILabel alloc] initWithFrame:cell.contentView.frame];
                label.text = @"加载失败，点击重试";
                label.font = [UIFont fontWithName:@"Arial" size:14];
                label.textColor = [UIColor darkGrayColor];
                label.textAlignment = NSTextAlignmentCenter;
                [cell.contentView addSubview:label];
                
            } else if(cell.tag == -3){//显示失败提示
                UILabel* label = [[UILabel alloc] initWithFrame:cell.contentView.frame];
                label.text = @"网络异常，点击重试";
                label.font = [UIFont fontWithName:@"Arial" size:14];
                label.textColor = [UIColor darkGrayColor];
                label.textAlignment = NSTextAlignmentCenter;
                [cell.contentView addSubview:label];
            }
            return cell;
            
        } else {
            OASendApplyNodeViewCell *cell = [[OASendApplyNodeViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
            //添加分割线
            UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 65, SuperWidth, 1)];
            lineView.backgroundColor = [UIColor groupTableViewBackgroundColor];
            [cell.contentView addSubview:lineView];
            
            NSDictionary *mDictionary = [self.appleNodeArray objectAtIndex:indexPath.row];
            NSString *org = [mDictionary objectFormatForKey:@"org"];
            NSString *dept = [mDictionary objectFormatForKey:@"dept"];
            
            cell.compLable.text = org && ![org isEqualToString:@""] ? org : @"未知";
            cell.depLable.text = dept && ![dept isEqualToString:@""] ? dept : @"未知";
            cell.postLable.text = [mDictionary objectFormatStringForKey:@"tnodename"];
            cell.numberLable.text = [NSString stringWithFormat:@"%ld",indexPath.row + 1];
            
            //节点是否修改消息
            NSDictionary *dictionary = [self.appleNodeArray objectAtIndex:indexPath.row];
            BOOL rankIdstatus = [[dictionary objectForKey:@"rankIdstatus"] boolValue];
            if (rankIdstatus) {
                cell.modifButton.hidden = NO;
                cell.selectionStyle = UITableViewCellSelectionStyleDefault;
                cell.incoBgLable.backgroundColor = [UIColor colorWithRed:255/255.0 green:128/255.0 blue:0/255.0 alpha:0.75];
                cell.incoTextLable.text = @"编辑节点";
            } else {
                cell.modifButton.hidden = YES;
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
            }
            
            return cell;
        }
    }
    
    //添加附件
    else if(indexPath.section == 2){
        GEInputTableViewCell *cell = [[GEInputTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        cell.bounds = CGRectMake(0, 0, cell.bounds.size.width, 48);
        
        if (indexPath.row < self.accessoryArray.count) {
            FileUploadModel *model = [self.accessoryArray objectAtIndex:indexPath.row];
            [self drawRowFileCell:cell model:model indexPath:indexPath];
        } else {
            UIImage *image = [UIImage imageNamed:@"button_bg_add"];
            UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(cell.frame.size.width/2-image.size.width/2, cell.frame.size.height/2-image.size.height/2, image.size.width, image.size.height)];
            [imageView setImage:image];
            [cell.contentView addSubview:imageView];
        }
        return cell;
    }
    
    return nil;
}

#pragma mark
#pragma mark - UITableViewDelegate

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [tableView setSeparatorInset:UIEdgeInsetsZero];
    }
    
    if ([tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [tableView setLayoutMargins:UIEdgeInsetsZero];
    }
    
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SuperWidth, 30)];
    view.backgroundColor = [UIColor clearColor];
    
    UIView *viewBackground = [[UIView alloc] initWithFrame:CGRectMake(10, 0, SuperWidth - 20, 30)];
    viewBackground.backgroundColor = [UIColor whiteColor];
    [view addSubview:viewBackground];
    
    UILabel *lable = [[UILabel alloc] initWithFrame:CGRectMake(15, 0, SuperWidth - 30, 29.5)];
    lable.textColor = [UIColor darkGrayColor];
    lable.font = [UIFont boldSystemFontOfSize:15];
    if(section == 0){
        lable.text = @"申请内容";
    } else if(section == 1){
        lable.text = @"审批流程";
    } else if(section == 2){
        lable.text = @"添加附件";
    }
    [view addSubview:lable];
    
    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 29, SuperWidth, 1)];
    lineView.backgroundColor = [UIColor groupTableViewBackgroundColor];
    [view addSubview:lineView];
    
    return view;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 30;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.section == 0) {
        if(self.appleContentState == 3){
            AutoTextTableViewCell *cell = [[AutoTextTableViewCell alloc] init];
            [cell setDataArray:self.appleModeData];
            return cell.contentView.frame.size.height;
        } else return 54;
    }
    
    if(indexPath.section == 1) return self.appleNodeArray.count>0 ? 66 : 44;
    if (indexPath.section == 2) return 48;
    return 44;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    //审批流程
    if (indexPath.section == 1){
        GEInputTableViewCell *viewCell = (GEInputTableViewCell*)[tableView cellForRowAtIndexPath:indexPath];
        if (indexPath.row == 0 && viewCell.tag != 0 && self.appleNodeArray.count <=0) { //重新获取数据
            [self getFlowNetWorkData];
        } else if(self.appleNodeArray.count>0){//数据节点修改/添加
            NSDictionary *dictionary = [self.appleNodeArray objectAtIndex:indexPath.row];
            NSInteger rankId = [[dictionary objectForKey:@"rankId"] integerValue];
            BOOL rankIdstatus = [[dictionary objectForKey:@"rankIdstatus"] boolValue];
            
            //添加节点消息
            if (rankIdstatus) {
                //机构数类型(1:公文机构职位树,2:消息管理机构职位树,3:通讯录关联公司列表树，4:申请，代发公司，部门查询调用接口,5: 发起申请节点修改树
                ServiceParametModel *model = [[ServiceParametModel alloc] init];
                model.methodName = @"OA_GetTree_Public";
                [model setValue:[NSNumber numberWithInteger:rankId] forKey:@"userid"];
                [model setValue:@5 forKey:@"type"];
                
                ThreeDataViewController *view = [[ThreeDataViewController alloc] initWithStyle:SelectOne serviceParamet:model];
                view.backResultDelagate = self;
                [view setTitle:@"选择审批节点"];
                [view setTagKey:@"NodePeople"];
                [view setSender:[NSNumber numberWithInteger:indexPath.row]];
                [self.navigationController pushViewController:view animated:YES];
            }
        }
    }
    
    //添加附件
    else if (indexPath.section == 2 && indexPath.row ==([self tableView:nil numberOfRowsInSection:2] - 1)) {
        UploadViewController *abstractView = [[UploadViewController alloc] init];
        [abstractView setNumberType:@"2" extension:nil];
        
        abstractView.key = @"AccessoryFile";
        abstractView.backResultDelagate = self;
        [self.navigationController pushViewController:abstractView animated:YES];
    }
    
    //附件预览
    else if (indexPath.section == 2){
        FileUploadModel *model = [self.accessoryArray objectAtIndex:indexPath.row];
        PreviewLocalFileHelper *preview = [PreviewLocalFileHelper instantiation];
        [preview previewViewController:self localFile:model.filePath];
    }
    
}

- (void)getOrderBascInfo
{
    NSDictionary *orderInfo = self.value;
    NSString *orderId = [orderInfo objectFormatStringForKey:@"ID"];//订单ID
    
    //@状态（全部、供毕、正供、待供）
    WebServiceCommonRequest *content = [[WebServiceCommonRequest alloc] init];
    [content setInterfaceType:InterfaceTypeGroup];
    [content setModuleType:@"OA_APPLY_ORGER_INFO"];
    [content setResultBackType:ResultBackTypeCommonUnordered];
    [content addParameterKey:@"订单ID" value:orderId];
    
    [content startAsyncConnectCompleted:^(ServiceResultModel *result, NSDictionary *userInfo) {
        //添加数据，刷新页面
        NSArray *firstArray = nil;
        if(result.resultArray && result.resultArray.count>0)
            firstArray = [result.resultArray firstObject];
        
        if(firstArray && firstArray.count>0){
            self.appleModeData = [self appleOrderModelFiledHanleArray:firstArray];
            self.appleContentState = 3;
            [self.tableView reloadData];
        } else {
            //未找到数据
            self.appleContentState = 1;
            [self.tableView reloadData];
        }
        [self.tableView reloadData];
        
    } failed:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        self.appleContentState = 2;
        [self.tableView reloadData];
        
    } abnormal:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        self.appleContentState = 2;
        [self.tableView reloadData];
        
    }];
}

- (NSMutableArray*)appleOrderModelFiledHanleArray:(NSArray*)array
{
    NSMutableArray *approval = [NSMutableArray array];
    if(array && array.count > 0){
        NSDictionary *dictionary = array.firstObject;
        for (NSString *key in dictionary) {
            NSString *keyString = [NSString stringWithFormat:@"%@：", key];
            NSDictionary *valueDic = [NSDictionary dictionaryWithObject:dictionary[key] forKey:keyString];
            [approval addObject:valueDic];
        }
    }
    return approval;
}


#pragma mark -
#pragma mark Button Event

- (void)delFileSelector:(GEObjectButton*)button
{
    NSArray *array = button.object;
    NSInteger section = [array[0] integerValue];
    id delValue = array[1];
    
    if (section == 2 && self.accessoryArray.count>0) {
        NSInteger index = [self.accessoryArray indexOfObject:delValue];
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:index inSection:2];
        
        NSArray *delIndexPath = [NSArray arrayWithObjects:indexPath, nil];
        [self.accessoryArray removeObject:delValue];
        [self.tableView beginUpdates];
        [self.tableView deleteRowsAtIndexPaths:delIndexPath withRowAnimation:UITableViewRowAnimationLeft];
        [self.tableView endUpdates];
    }
    
}

#pragma mark - NetWork

- (void)getFlowNetWorkData
{
    //显示进度条
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:1];
    GEInputTableViewCell *applyCell = (GEInputTableViewCell*)[self.tableView cellForRowAtIndexPath:indexPath];
    applyCell.tag = -1;
    NSArray *reloadIndexPath = [NSArray arrayWithObjects:indexPath, nil];
    [self.tableView reloadRowsAtIndexPaths:reloadIndexPath withRowAnimation:UITableViewRowAnimationNone];
    
    //@状态（全部、供毕、正供、待供）
    WebServiceCommonRequest *content = [[WebServiceCommonRequest alloc] init];
    [content setInterfaceType:InterfaceTypeERP];
    [content setModuleType:@"OA_APPLY_ORGER_MODE_TYPE"];
    [content setResultBackType:ResultBackTypeCommonUnordered];
    [content addParameterKey:@"流程模板" value:@"[SYS]浇筑令审核"];
    
    [content startAsyncConnectCompleted:^(ServiceResultModel *result, NSDictionary *userInfo) {
        //添加数据，刷新页面
        NSArray *firstArray = nil;
        if(result.resultArray && result.resultArray.count>0)
            firstArray = [result.resultArray firstObject];
        
        if(firstArray && firstArray.count>0){
            //继续获取模板信息
            NSDictionary *mDictionary = firstArray.firstObject;
            NSString *processId = [mDictionary objectFormatStringForKey:@"processId"];
            [self getNetWorkNodeData:processId];
        } else {
            applyCell.tag = -2;
            NSArray *reloadIndexPath = [NSArray arrayWithObjects:indexPath, nil];
            [self.tableView reloadRowsAtIndexPaths:reloadIndexPath withRowAnimation:UITableViewRowAnimationNone];
        }
        
    } failed:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        applyCell.tag = -2;
        NSArray *reloadIndexPath = [NSArray arrayWithObjects:indexPath, nil];
        [self.tableView reloadRowsAtIndexPaths:reloadIndexPath withRowAnimation:UITableViewRowAnimationNone];
        
    } abnormal:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        applyCell.tag = -3;
        NSArray *reloadIndexPath = [NSArray arrayWithObjects:indexPath, nil];
        [self.tableView reloadRowsAtIndexPaths:reloadIndexPath withRowAnimation:UITableViewRowAnimationNone];
        
    }];
}

- (void)getNetWorkNodeData:(NSString*)processId
{
    NSDictionary *orderInfo = self.value;
    NSString *templateId = [orderInfo objectFormatStringForKey:@"ID"];//订单ID
    
    //设置流程信息
    self.processId = processId;
    self.templateId = templateId;
    
    //判断有无数据，无数据就不显示任何控件
    if (!(processId && processId.length>0 && templateId && templateId.length>0)) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:1];
        GEInputTableViewCell *applyCell = (GEInputTableViewCell*)[self.tableView cellForRowAtIndexPath:indexPath];
        applyCell.tag = 0;
        NSArray *reloadIndexPath = [NSArray arrayWithObjects:indexPath, nil];
        [self.tableView reloadRowsAtIndexPaths:reloadIndexPath withRowAnimation:UITableViewRowAnimationNone];
        return;
    }
    
    //清理所有数据
    [self.appleNodeArray removeAllObjects];
    NSIndexSet *sectionToReload = [[NSIndexSet alloc] initWithIndex:1];
    [self.tableView beginUpdates];
    [self.tableView reloadSections:sectionToReload withRowAnimation:UITableViewRowAnimationAutomatic];
    [self.tableView endUpdates];
    
    //显示进度条
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:1];
    GEInputTableViewCell *applyCell = (GEInputTableViewCell*)[self.tableView cellForRowAtIndexPath:indexPath];
    applyCell.tag = -1;
    NSArray *reloadIndexPath = [NSArray arrayWithObjects:indexPath, nil];
    [self.tableView reloadRowsAtIndexPaths:reloadIndexPath withRowAnimation:UITableViewRowAnimationNone];
    
    UserLoginNSCoding *userInfo = [NSKeyedArchiverUserLogin getUserLoginData];
    NSNumber *orgId = [NSNumber numberWithInteger:[userInfo.CorpId integerValue]];
    NSNumber *deptId = [NSNumber numberWithInteger:[userInfo.DeptId integerValue]];
    
    //获取节点数据
    ServiceParametModel *model = [[ServiceParametModel alloc] init];
    [model setValue:processId forKey:@"processId"];//流程ID
    [model setValue:templateId forKey:@"templateId"];//类型ID
    [model setValue:orgId forKey:@"orgId"];
    [model setValue:deptId forKey:@"deptId"];
    
    ServiceConnect *content = [[ServiceConnect alloc] initWithMethodName:@"OA_getNewApproval" dataArray:model];
    [content startConnectNetworkCompleted:^(ServiceResultModel *result, NSDictionary *userInfo) {
        //添加数据，刷新页面
        if(result.resultArray && result.resultArray.count>0){
            NSArray *array = result.resultArray;
            [self.appleNodeArray addObjectsFromArray:array];
            
            NSIndexSet *sectionToReload = [[NSIndexSet alloc] initWithIndex:1];
            [self.tableView beginUpdates];
            [self.tableView reloadSections:sectionToReload withRowAnimation:UITableViewRowAnimationAutomatic];
            [self.tableView endUpdates];
        } else {
            applyCell.tag = -2;
            NSArray *reloadIndexPath = [NSArray arrayWithObjects:indexPath, nil];
            [self.tableView reloadRowsAtIndexPaths:reloadIndexPath withRowAnimation:UITableViewRowAnimationNone];
        }
    } failed:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        applyCell.tag = -2;
        NSArray *reloadIndexPath = [NSArray arrayWithObjects:indexPath, nil];
        [self.tableView reloadRowsAtIndexPaths:reloadIndexPath withRowAnimation:UITableViewRowAnimationNone];
        
    } abnormal:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        applyCell.tag = -3;
        NSArray *reloadIndexPath = [NSArray arrayWithObjects:indexPath, nil];
        [self.tableView reloadRowsAtIndexPaths:reloadIndexPath withRowAnimation:UITableViewRowAnimationNone];
    }];
}

#pragma mark -
#pragma mark BackResultDataDelagate

- (void)backResultDataKey:(id)key dataValue:(id)backValue
{
    [super backResultDataKey:key dataValue:backValue];
    NSArray *array = backValue;
    if (!(array && array.count>0)) return;
    
    if([key isEqualToString:@"AccessoryFile"]){
        //添加附件
        if ([backValue isKindOfClass:[NSArray class]]) {
            NSMutableArray *insertIndexPath = [NSMutableArray array];
            for (int i=0;i<array.count;i++) {
                id value = [array objectAtIndex:i];
                NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:2];
                [insertIndexPath addObject:indexPath];
                [self.accessoryArray insertObject:value atIndex:0];
            }
            
            if (insertIndexPath.count>0) {
                [self.tableView beginUpdates];
                [self.tableView insertRowsAtIndexPaths:insertIndexPath withRowAnimation:UITableViewRowAnimationTop];
                [self.tableView endUpdates];
            }
        }
    }
}

- (void) backResultDataKey:(id)keyValue sender:(id)senderValue dataValue:(id)backValue
{
    [super backResultDataKey:keyValue sender:senderValue dataValue:backValue];
    if (!backValue) return;
    
    //节点数据添加
    if([keyValue isEqualToString:@"NodePeople"]){
        NSInteger row = [senderValue integerValue];
        NSDictionary *backDictionary = backValue;
        NSDictionary *mDictionary = [self.appleNodeArray objectAtIndex:row];
        
        NSMutableDictionary *addValueDictionary = [[NSMutableDictionary alloc] initWithDictionary:mDictionary];
        [addValueDictionary setObject:[backDictionary objectFormatForKey:@"name"] forKey:@"tnodename"];
        [addValueDictionary setObject:[backDictionary objectFormatForKey:@"orgname"] forKey:@"org"];
        [addValueDictionary setObject:[backDictionary objectFormatForKey:@"deptname"] forKey:@"dept"];
        [addValueDictionary setObject:[backDictionary objectFormatForKey:@"id"] forKey:@"postid"];
        [self.appleNodeArray setObject:addValueDictionary atIndexedSubscript:row];
        
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:row inSection:1];
        NSArray *insertIndexPath = @[indexPath];
        [self.tableView beginUpdates];
        [self.tableView reloadRowsAtIndexPaths:insertIndexPath withRowAnimation:UITableViewRowAnimationAutomatic];
        [self.tableView endUpdates];
    }
}

#pragma mark clean All Data

- (void)cleanAllData
{
    //清理流程页面数据
    NSIndexPath *indexPathss = [NSIndexPath indexPathForRow:0 inSection:1];
    GEInputTableViewCell *applyCellClean = (GEInputTableViewCell*)[self.tableView cellForRowAtIndexPath:indexPathss];
    applyCellClean.tag = 0;
    NSArray *reloadIndexPath = [NSArray arrayWithObjects:indexPathss, nil];
    [self.tableView reloadRowsAtIndexPaths:reloadIndexPath withRowAnimation:UITableViewRowAnimationNone];
    
    //清理流程所有数据
    [self.appleNodeArray removeAllObjects];
    NSIndexSet *sectionToReload = [[NSIndexSet alloc] initWithIndex:1];
    [self.tableView beginUpdates];
    [self.tableView reloadSections:sectionToReload withRowAnimation:UITableViewRowAnimationAutomatic];
    [self.tableView endUpdates];
}

@end
